package com.flute.framework.search.strategy;

import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;

import com.flute.framework.search.LayerPayLoadFunction;
import com.flute.framework.search.LayerPayloadTermQuery;
import com.flute.tools.util.StringUtil;

public abstract class AbstractTermSearchStrategy extends AbstractSearchStrategy {

	@Override
	public Object getQuery(String string) {
		return getQuery(string, null);
	}

	public Object getQuery(String string, String sorter) {
		return getQuery(string, sorter, 1f);
	}

	@Override
	public Object getQuery(String string, String sorter, float boost) {
		string = StringUtil.getStandardString(string);
		String[] strings = process(string).split(StringUtil.UNIQUE_STRING);

		if (strings.length == 1) {
			if (!StringUtil.isNullOrEmpty(strings[0])) {
				return getTermQuery(strings[0], sorter, boost);
			} else {
				return null;
			}
		} else {
			BooleanQuery bq = new BooleanQuery();
			for (String s : strings) {
				if (!StringUtil.isNullOrEmpty(s)) {
					if (isAllWordMeet()) {
						bq.add(getTermQuery(s, sorter, boost),
								BooleanClause.Occur.MUST);
					} else {
						bq.add(getTermQuery(s, sorter, boost),
								BooleanClause.Occur.SHOULD);
					}
				}
			}
			if (bq.clauses().size() > 0) {
				return bq;
			} else {
				return null;
			}
		}

	}

	private Query getTermQuery(String text, String sorter, float boost) {
		Query q = new LayerPayloadTermQuery(new Term(fieldName, text),
				new LayerPayLoadFunction(), sorter);
		q.setBoost(boost);
		
		return q;
	}

	public abstract String process(String string);

	public abstract boolean isAllWordMeet();
}
